package com.atguigu.lease.common.utils;

import com.atguigu.lease.common.exception.LeaseException;
import com.atguigu.lease.common.result.ResultCodeEnum;
import io.jsonwebtoken.*;
import io.jsonwebtoken.security.Keys;

import javax.crypto.SecretKey;
import java.util.Date;

public class JwtUtil {

    private static SecretKey secretKey = Keys.hmacShaKeyFor("z6ClbcXj6xbC3p4AsoRijuCGBEWUCOhf".getBytes());

    //创建token
    public static String createToken(Long userId, String username) {
        String token = Jwts.builder()//设置头部信息
                .setExpiration(new Date(System.currentTimeMillis() + 365 * 24 * 60 * 60 * 1000L))//设置过期时间
                .setSubject("LOGIN_USER")//设置主题
                .claim("userId", userId)//设置自定义属性
                .claim("username", username)//设置自定义属性
                .signWith(secretKey, SignatureAlgorithm.HS256)//设置签名算法和密钥
                .compact();//生成token
        return token;
    }

    //解析token
    public static Claims parseToken(String token) {
        if (token == null) {
            throw new LeaseException(ResultCodeEnum.ADMIN_LOGIN_AUTH);
        }

        try{
            JwtParser jwtParser = Jwts.parserBuilder()//创建解析器
                    .setSigningKey(secretKey)//设置签名密钥
                    .build();//构建解析器
            Jws<Claims> claimsJws = jwtParser.parseClaimsJws(token);//解析token
            return claimsJws.getBody();
        } catch (ExpiredJwtException e){
            //抛出token过期异常
            throw new LeaseException(ResultCodeEnum.TOKEN_EXPIRED);
        }catch (JwtException e){
            //抛出token非法异常
            throw new LeaseException(ResultCodeEnum.TOKEN_INVALID);
        }
    }

    public static void main(String[] args) {
        System.out.println(createToken(1L, "admin"));
    }
}
